import Taro , { Component } from '@tarojs/taro';
import { View, Text , Button} from '@tarojs/components';
import NavigationBar from '../../../components/navigationBar/index';
import CardBox from '../../../components/card-record';
import './index.scss';
import { getCardInfo, adminAllot } from '../../../services/user';
import { CARD_STATUS } from '../../../utils/config';

export default class Index extends Component {

   config = {
       navigationBarTitleText: '兑换卡'
  }

  state = {
    agencyId: null,
    list: [],
    navigationBarHeight: Taro.getStorageSync('navigationBarHeight'),
  }

  componentWillMount () {
    this.setState({
      agencyId: this.$router.params.id
    })
  }
  componentDidMount () {
    this.scanToAdd()
  }
  componentWillReceiveProps (nextProps,nextContext) {}
  componentWillUnmount () {}
  componentDidShow () {}
  componentDidHide () {}
  componentDidCatchError () {}
  componentDidNotFound () {}

  scanToAdd() {
    let self = this;
    let tempArr = [...this.state.list]
    Taro.scanCode({
      onlyFromCamera: true,
      success: res => {
        getCardInfo({
          card_no: res.result
        }).then(data => {
          if (tempArr.find(item => {
            return item.card_no === data.card_no
          })) {
            Taro.showToast({
              title: '请勿重复添加',
              icon: 'none'
            })
            return
          }
          tempArr.push(data)
          self.setState({
            list: tempArr
          })
        })
      }
    })
  }

  delete(number) {
    let tempList = [...this.state.list]
    tempList = tempList.filter(item => {
      return item.card_no !== number
    })
    this.setState({
      list: tempList
    })
  }

  allot() {
    let tempList = [...this.state.list]
    let card_nos = tempList.map(item => {
      return item.card_no
    })
    adminAllot({
      id: this.state.agencyId,
      card_nos: card_nos
    }).then(res => {
      Taro.setStorageSync('outputData', res)
      Taro.navigateTo({
        url: `/subPackageWork/pages/storage-success/index?type=1`
      })
    })
  }

  render() {
    const {list} = this.state
    return (
      <View className="page" style={`margin-top: ${navigationBarHeight}`}>
        <NavigationBar text="兑换卡" />
        {list.map(card => {
          if (card) return <CardBox onDel={this.delete.bind(this)} key={card.id} type={4} cardType={card.attr_name} number={card.card_no} />
        })}
        <View className="btn-wrapper">
          <View className="btn add" onClick={this.scanToAdd}>继续添加</View>
          <View className="btn output" onClick={this.allot}>全部出库({list.length})</View>
        </View>
      </View>
    );
  }
}
